<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="props?.data?.id ? $t('reason.editDia.编辑原因') : $t('reason.editDia.新增原因')"
    width="500px"
  >
    <LangTabs v-model="lang" />
    <el-form :model="formData" label-width="160px" ref="formRef" :rules="rules">
      <el-form-item :label="$t('reason.editDia.原因名称')" :prop="'name' + lang">
        <el-input v-model="formData['name' + lang]" :placeholder="$t('reason.editDia.请输入原因名称')"/>
      </el-form-item>
      <el-form-item :label="$t('reason.editDia.原因类型')" prop="type">
        <el-select v-model="formData.type">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup>
import { ref, watch } from "vue";
import Dialog from "@/components/dialog.vue";
import EditorWang from "@/components/editorWang.vue";
import Api from "@/config/api/api";
import { setAttrLangs } from "@/i18n/tools";
import LangTabs from "@/components/langTabs.vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";

const { locale, t } = useI18n();
const lang = ref(locale.value);
const show = defineModel();
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});
const options = [
  { label: t('reason.违规下架'), value: 1 },
  // { label: "商品审核拒绝", value: 2 },
  { label: t('reason.入驻审核拒绝'), value: 3 },
  { label: t('reason.会员取消订单'), value: 4 },
  { label: t('reason.仅退款'), value: 5 },
  { label: t('reason.退货退款'), value: 6 },
];
const emit = defineEmits(["success"]);
watch(()=>show.value, (val) => {
  if (val) {
    if (props?.data?.id) {
      formData.value = props.data;
    }
    if (props?.data?.type) {
      formData.value.type = props.data.type;
    }
  }
});
const formData = ref({
  type: "",
});
const rules = ref({
  type: [{ required: true, message: t('reason.editDia.请选择原因类型'), trigger: "blur" }],
});
setAttrLangs(formData.value, "name", "");
setAttrLangs(rules.value, "name", [
  { required: true, message: t('reason.editDia.请输入原因名称'), trigger: "blur" },
]);
const formRef = ref();
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const params = {
        ...formData.value,
        id: props?.data?.id,
        status: 1,
        sort: 1,
      };
      Api[props?.data?.id ? "editReason" : "addReason"](params).then(
        (res) => {
          const { status } = res;
          if (status === 200) {
            ElMessage.success(t('reason.editDia.操作成功'));
            emit("success");
            close();
          }
        }
      );
    }
  });
};
const close = () => {
  formData.value = {
    type: ""
  }
  setAttrLangs(formData.value, "name", "");
  formRef.value.resetFields();
  show.value = false;
  lang.value = locale.value;
};
</script>
